#!D:/CodeEnvmt/Python/Python38/python.exe
#第一行是告知python编译器位置
# -*- coding: utf-8 -*-
import json
from os import name
import time
import muggle_ocr
import requests
from PIL import Image
import hashlib
import mysql.connector
import codecs

my_url = "http://my.scu.edu.cn/userPasswordValidate.portal"
captcha_url = "http://zhjw.scu.edu.cn/img/captcha.jpg"  # 验证码地址
index_url = "http://zhjw.scu.edu.cn/"  # 主页地址
index_url = "http://zhjw.scu.edu.cn/index.jsp"
login_url = "http://zhjw.scu.edu.cn/j_spring_security_check"  # 登录接口
already_select_course_url = "http://zhjw.scu.edu.cn/student/courseSelect/thisSemesterCurriculum/callback"  # 已选课程查询地址
header = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'DNT': '1',
    'Host': 'zhjw.scu.edu.cn',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3782.0 Safari/537.36 Edg/76.0.152.0'
}

my_header = {
    "Host": "my.scu.edu.cn",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
    "Accept-Encoding": "gzip, deflate",
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": "160",
    "Origin": "http://my.scu.edu.cn",
    "Connection": "keep-alive",
    #    "Referer": "http://my.scu.edu.cn/",
    "Upgrade-Insecure-Requests": "1"
}
sdk = muggle_ocr.SDK(model_type=muggle_ocr.ModelType.Captcha)

with open("src/res/info.txt", "r", encoding='utf-8') as f:
    info = f.readlines()

j_username = info[0].strip('\n')

j_password = info[1]
mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="123456789ft",
    database="scucourseman")
cursor=mydb.cursor()


def login2(session):
    captcha_bytes = session.get(url=captcha_url, headers=header).content
    text = sdk.predict(image_bytes=captcha_bytes)
    if len(text) != 4:
        return None
    login_data = {
        'j_username': j_username,
        'j_password': hashlib.md5(j_password.strip('\n').encode()).hexdigest(),
        'j_captcha': text
    }
    try:
        response = session.post(
            url=login_url, headers=header, data=login_data).text
        if "欢迎您" in response:
            f=open('src/res/result.txt','w',encoding='utf-8')
            f.write(response)
            f.close
            return "success"
        else:
            return "failed"
    except Exception as e:
        time.sleep(1)
        return None

# 这个函数用来获取所有的已选课程的信息
def getAlreadyCourseInfo(session):
    
    already_select_course_info_list = []
    try:
        response = session.get(
            url=already_select_course_url, headers=header).text
        for each in json.loads(response)['xkxx'][0]:
            already_select_course_info_list.append([
                json.loads(response)['xkxx'][0][each]['courseName'],  # 课程名称 0
                json.loads(response)['xkxx'][0][each]['attendClassTeacher'],  # 课程教师 1
                json.loads(response)['xkxx'][0][each]['id']['coureNumber'],  # 课程号 2
                json.loads(response)['xkxx'][0][each]['id']['coureSequenceNumber'],  # 课序号 3
                json.loads(response)['xkxx'][0][each]['timeAndPlaceList'][0]['campusName'],  # 校区 4
                json.loads(response)['xkxx'][0][each]['timeAndPlaceList'][0]['teachingBuildingName'],  # 在哪个教学楼 5
                json.loads(response)['xkxx'][0][each]['timeAndPlaceList'][0]['classroomName'],  # 在哪个教室 6
                json.loads(response)['xkxx'][0][each]['timeAndPlaceList'][0]['classDay'],  # 周几 7
                json.loads(response)['xkxx'][0][each]['timeAndPlaceList'][0]['classSessions'],  # 第几节 8
                json.loads(response)['xkxx'][0][each]['timeAndPlaceList'][0]['continuingSession'],  # 持续多少节 9
                json.loads(response)['xkxx'][0][each]['timeAndPlaceList'][0]['weekDescription'],  # 上几周 10
                json.loads(response)['xkxx'][0][each]['examTypeName'], #课程的考核方式 11
                json.loads(response)['xkxx'][0][each]['programPlanName'], #课程属于什么培养方案 12
                json.loads(response)['xkxx'][0][each]['unit'], #课程的学分数 13
                json.loads(response)['xkxx'][0][each]['coursePropertiesName'] #课程的属性，必修/选修/任选 14
            ])
        
        return already_select_course_info_list
    except Exception as e:
        print("def getAlreadyCourse() 出现问题:" + str(e))
        return None 


def sqlInsert(session):
    val=[] #用于存放要插入数据库的数据的列表
    course_list=getAlreadyCourseInfo(session) #获取已选课程和具体信息的列表
    """
    对stu_order表进行处理
    """
    #看sut_order中有无该学号
    cursor.execute('SELECT COUNT(*) FROM stu_order WHERE xuehao=%s' %j_username)
    result=cursor.fetchall()
    if result[0][0]==0:#没有该结果，执行插入操作
        sql='INSERT INTO stu_order VALUES(%s,%s,%s)' #xuehao,姓名,order
        #向val中插入学号
        val.append(j_username) 
        
        #向val中插入姓名
        temp=[]
        #根据得到的response，读取文件的特定行，再对末尾的换行符进行处理
        with codecs.open("src/res/result.txt", "r", encoding='utf-8') as f:
            for i in f.readlines()[584:585]:
                temp.append(i)
        name_str=temp[0]
        val.append(name_str)
        
        #向val中插入序号
        cursor.execute('SELECT COUNT(*) FROM stu_order')
        result=cursor.fetchall() #获取现在表中到底有多少个数据
        a=result[0][0]
        val.append(a+1)
        
        #执行插入stu_order的语句
        cursor.execute(sql,val) 
        mydb.commit()
    
    """
    对stu_course表进行处理
    """
    val.clear() #把容器清空
    #首先获取该学生的序号
    cursor.execute('SELECT stu_order FROM stu_order WHERE xuehao=%s' %j_username)
    result=cursor.fetchall()
    order=result[0][0]
    
    #看stu_course中有无该学生序号
    cursor.execute('SELECT * FROM stu_course WHERE stu_order=%s' %order)
    result=cursor.fetchall()
    if not result: #没有该学生的序号，将该生所有课程插入
        for each in course_list:
            val.append([order,each[0],each[2],each[3]]) #向val中插入值
        
        sql='INSERT INTO stu_course VALUES(%s,%s,%s,%s)'
        cursor.executemany(sql,val) #执行sql语句
        mydb.commit()
    
    """
    对cou_info进行处理
    """
    
    #对每一个课程，查看cou_info表中有无记录
    for each in course_list:
        sql='SELECT * FROM cou_info WHERE c_name=%s AND c_num=%s AND c_seq=%s'
        temp=[each[0],each[2],each[3]]
        cursor.execute(sql,temp)
        result=cursor.fetchall()
        if not result: #要是没有该记录就插入 (c_name,c_num,c_seq,c_teacher,c_locate,c_time,c_con_time )
            val=[each[0],each[2],each[3],each[1],each[4]+'\n'+each[5]+'\n'+each[6],'周{}第{}-{}小节'.format(each[7],each[8],each[8]+each[9]-1),each[10]]
            sql="INSERT INTO cou_info VALUES(%s,%s,%s,%s,%s,%s,%s)"
            cursor.execute(sql,val) #执行sql语句
            mydb.commit()
    
    """
    对cou_loc_time进行处理
    """
    val.clear()
    #对每一个课程，查看cou_loc_time中有无记录
    for each in course_list:
        sql='SELECT * FROM cou_loc_time WHERE c_name=%s AND c_num=%s AND c_seq=%s'
        temp=[each[0],each[2],each[3]]
        cursor.execute(sql,temp)
        result=cursor.fetchall()
        if not result: #要是没有该记录就插入（c_num,c_seq,c_name,c_campus,c_building,c_classroom,c_weekday,c_session）
            val=[each[2],each[3],each[0],each[4],each[5],each[6],each[7],each[8]]
            sql='INSERT INTO cou_loc_time VALUES(%s,%s,%s,%s,%s,%s,%s,%s)'
            cursor.execute(sql,val)
            mydb.commit()
    
    """
    对cou_other_info进行处理
    """
    val.clear()
    #对每一个课程，查看cou_other_info中有无记录
    for each in course_list:
        sql='SELECT * FROM cou_other_info WHERE c_name=%s'
        temp=[each[0]]
        cursor.execute(sql,temp)
        result=cursor.fetchall()
        if not result: #没有该课程的记录就插入 (c_name,c_type,c_credit,c_test,c_project)
            val=[each[0],each[14],each[13],each[11],each[12]]
            sql='INSERT INTO cou_other_info VALUES(%s,%s,%s,%s,%s)'
            cursor.execute(sql,val) #执行sql语句
            mydb.commit()
    

    return None
 

def main(session):
    
    # ------------login-------------
    i=1
    ifLogin=False
    while i<5: #尝试十次
        # 登录
        loginResponse = login2(session)
        if loginResponse == "success":
            ifLogin=True
            break
        else:
            time.sleep(2)
            i+=1
    
    if ifLogin==False: #登录失败显示错误信息，需要重新登录
        print('n')
    else: #登录成功，进入界面
        sqlInsert(session)
        print("y")
        

if __name__ == "__main__":

    session = requests.session()
    main(session)

